package com.chenxinzhi.codetools.ui

import androidx.compose.foundation.layout.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.chenxinzhi.codetools.listener.MyModuleListener
import com.chenxinzhi.codetools.message.message
import com.intellij.database.dataSource.DataSourceStorage
import com.intellij.database.dataSource.LocalDataSource
import com.intellij.database.model.RawDataSource
import com.intellij.database.psi.DataSourceManager
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindowManager
import org.jetbrains.jewel.foundation.theme.JewelTheme
import org.jetbrains.jewel.ui.component.*
import org.jetbrains.jewel.ui.theme.simpleListItemStyle
import java.util.stream.Collectors


val commonNoModuleDisable = listOf(message("box.disable-module"))

@Composable
fun CodeGen(project: Project) {

    var step by remember { mutableStateOf(0) }
    var modules by remember { mutableStateOf(listOf<com.intellij.openapi.module.Module>()) }
    val modulesName by remember { derivedStateOf { modules.map { it.name } } }
    var projectCheckIndex by remember { mutableStateOf(0) }
    var serviceCheck by remember { mutableStateOf("") }
    val serviceModule by remember {
        derivedStateOf {
            modulesName.filter { it.endsWith("service") }
        }
    }
    var serviceApiCheck by remember { mutableStateOf("") }
    val serviceApiModule by remember {
        derivedStateOf {
            modulesName.filter { it.endsWith("api") }
        }
    }
    var moduleCheck by remember { mutableStateOf("") }
    val moduleService by remember {
        derivedStateOf {
            modulesName
        }
    }
    var dataSources by remember { mutableStateOf(listOf<RawDataSource>()) }
    val dataSourceNames by remember {
        derivedStateOf { dataSources.map { it.name } }
    }
    var dataSourceCheck by remember { mutableStateOf("") }
    LaunchedEffect(Unit) {
        { modules = ModuleManager.getInstance(project).modules.toList() }.apply {
            invoke()
            MyModuleListener.listenerFlow.emit(this)
        }
    }
    Column(modifier = Modifier.padding(10.dp)) {
        if (step == 0) {
            Row(
                horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically
            ) {
                RadioButtonRow(
                    text = message("cloud.project"),
                    selected = projectCheckIndex == 0,
                    onClick = { projectCheckIndex = 0 })
                RadioButtonRow(
                    text = message("boot.project"),
                    selected = projectCheckIndex == 1,
                    onClick = { projectCheckIndex = 1 })
            }
            Spacer(modifier = Modifier.height(10.dp))
            if (projectCheckIndex == 0) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                ) {
                    Text(message("select.service"))
                    ListComboBox(
                        items = serviceModule,
                        modifier = Modifier.width(200.dp),
                        isEditable = false,
                        maxPopupHeight = 150.dp,
                        onSelectedItemChange = { serviceCheck = it },
                        noElementText = message("box.disable-module"),
                        listItemContent = { item, isSelected, isFocused, isItemHovered, isPreviewSelection ->
                            SimpleListItem(
                                text = item,
                                state = ListItemState(isSelected, isItemHovered, isPreviewSelection),
                                style = JewelTheme.simpleListItemStyle,
                                contentDescription = item,
                            )
                        },

                        )
                }
                Spacer(modifier = Modifier.height(20.dp))
                Row(
                    verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Text(message("select.service-api"))
                    ListComboBox(
                        items = serviceApiModule,
                        modifier = Modifier.width(200.dp),
                        isEditable = false,
                        maxPopupHeight = 150.dp,
                        onSelectedItemChange = { serviceApiCheck = it },
                        noElementText = message("box.disable-module"),
                        listItemContent = { item, isSelected, isFocused, isItemHovered, isPreviewSelection ->
                            SimpleListItem(
                                text = item,
                                state = ListItemState(isSelected, isItemHovered, isPreviewSelection),
                                style = JewelTheme.simpleListItemStyle,
                                contentDescription = item,
                            )
                        },
                    )
                }

            } else {
                Row(
                    verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Text(message("select.module"))
                    ListComboBox(
                        items = moduleService,
                        modifier = Modifier.width(200.dp),
                        isEditable = false,
                        maxPopupHeight = 150.dp,
                        onSelectedItemChange = { moduleCheck = it },
                        noElementText = message("box.disable-module"),
                        listItemContent = { item, isSelected, isFocused, isItemHovered, isPreviewSelection ->
                            SimpleListItem(
                                text = item,
                                state = ListItemState(isSelected, isItemHovered, isPreviewSelection),
                                style = JewelTheme.simpleListItemStyle,
                                contentDescription = item,
                            )
                        },
                    )
                }
            }
            Spacer(modifier = Modifier.height(20.dp))
            Row(
                verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                DefaultButton(onClick = {
                    step = 1
                }) { Text(message("next.step")) }
            }
            Text(serviceCheck)
        }
        if (step == 1) {
            DisposableEffect(Unit) {
                val refresh = {
                    dataSources = DataSourceManager.getManagers(project)
                        .stream()
                        .flatMap { manager -> manager.getDataSources().stream() }
                        .collect(Collectors.toList())
                }.apply {
                    invoke()
                }
                project.messageBus.connect().subscribe(DataSourceStorage.TOPIC, object : DataSourceStorage.Listener {
                    override fun dataSourceChanged(dataSource: LocalDataSource?) {
                        refresh()
                    }

                    override fun dataSourceAdded(dataSource: LocalDataSource) {
                        refresh()
                    }

                    override fun dataSourceRemoved(dataSource: LocalDataSource) {
                        refresh()
                    }


                })
                onDispose {
                    project.messageBus.connect().disconnect()
                }
            }
            Row(
                verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                DefaultButton(onClick = {
                    ToolWindowManager.getInstance(project).getToolWindow("Database")?.activate { }
                }) { Text(message("open.datasource.tools")) }
            }
            Spacer(modifier = Modifier.height(10.dp))
            Row(
                verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Text(message("select.datasource"))
                ListComboBox(
                    items = dataSourceNames,
                    modifier = Modifier.width(200.dp),
                    isEditable = false,
                    maxPopupHeight = 150.dp,
                    onSelectedItemChange = { dataSourceCheck = it },
                    noElementText = message("no.database"),
                    listItemContent = { item, isSelected, isFocused, isItemHovered, isPreviewSelection ->
                        SimpleListItem(
                            text = item,
                            state = ListItemState(isSelected, isItemHovered, isPreviewSelection),
                            style = JewelTheme.simpleListItemStyle,
                            contentDescription = item,
                        )
                    },
                )
            }
            Spacer(modifier = Modifier.height(10.dp))
            Row(
                verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                DefaultButton(onClick = {
                    step = 0
                }) { Text(message("previous.step")) }
                DefaultButton(onClick = {
                    step = 3
                }) { Text(message("next.step")) }
            }
        }


    }

}

